from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse

from apps.user.models import BlogUser

# Create your views here.
from utils.StringUtil import StringUtil


def register(request):
    """渲染用户注册页面"""
    context = {}
    return render(request, 'user/register.html', context)


def login(request):
    """渲染用户登录页面"""
    context = {}
    return render(request, 'user/login.html', context)


def register_do(request):
    """实现用户注册"""
    context = {
        'code': 10000,
        'msg': 'ok'
    }
    # 获取用户信息
    username = request.POST.get('username')
    password = request.POST.get('password')
    # 校验用户名和密码不为空
    if username and password:
        # 对密码进行加密
        password = StringUtil.get_password_sha256(password)
        # 在加密之前，我们必须确保该用户不存
        try:
            BlogUser.objects.get(username=username, password=password)
            context['code'] = 20000  # 失败
            context['msg'] = '该用户已存在'
        except:
            BlogUser.objects.create(username=username, password=password)

    return JsonResponse(context)


def has_username(request):
    # 获取数据
    username = request.GET.get('username')
    # 查询数据库中是否已存在该用户名
    flag = True  # 表示用户名存在
    try:
        BlogUser.objects.get(username=username)
    except:
        flag = False  # 用户不存在
    context = {
        'is_exists': flag
    }
    return JsonResponse(context)


def login_ajax(request):
    """以ajax的方式登录"""
    # 获取用户名和密码
    username = request.POST.get('username')
    password = request.POST.get('password')
    # 对密码进行加密
    password = StringUtil.get_password_sha256(password)
    result = {
        'code': 10000,
        'msg': 'ok'
    }
    # 校验
    try:
        BlogUser.objects.get(username=username, password=password)
        # 没报错，代表存在，则登录成功
        resonpse = JsonResponse(result)
        # 设置cookie
        resonpse.set_cookie('username', username)
        # 再返回
        return resonpse
    except:
        # 报错了，代表失败，则登录失败
        result['code'] = 20000
        result['msg'] = '用户名或密码错误'
        return JsonResponse(result)


def login_out(request):
    """注销"""
    # 清除cookie
    response = redirect(reverse('user:login'))
    response.delete_cookie('username')
    return response
